<template>
	<view class="container">

		<view class="search-results-container">
			<form :model="saleOrder" label-width="80px">
				<view class="page-title">
					<text>{{ saleOrder.saleName1 }}</text>
				</view>

				<view style="margin-bottom: 5px;border-bottom: 2px solid #f5f5f5">
					<uni-row>
						<uni-col :span="22">
							<view :model="ecCustAddress"
								@tap="goToAddressDetail(saleOrder.agKunnr,saleOrder.agName,saleOrder.weKunnr,saleOrder.weName)">
								<uni-row>
									<uni-col :span="14">
										<div>
											<text>收货人：{{ecCustAddress.contactsName}}</text>
										</div>
									</uni-col>
									<uni-col :span="10">
										<div>
											<text>{{ecCustAddress.contactsPhone}}</text>
										</div>
									</uni-col>
								</uni-row>
								<div>
									<text>地址：{{ ecCustAddress.goodsDetailedAddress }}</text>
								</div>
							</view>
						</uni-col>
						<uni-col :span="2">
							<view class="clear-button" @click="clearAddress" v-if="ecCustAddress.goodsDetailedAddress">
								<text class="clear-icon">✖</text>
							</view>
						</uni-col>
					</uni-row>
				</view>

				<view style="margin-bottom: 5px;border-bottom: 2px solid #f5f5f5">
					<div>
						<text style="color: rgb(10, 186, 250);">特殊标志：{{saleOrder.customertab}}</text>
					</div>
					<uni-row>
						<uni-col :span="22">
							<view :model="receive" class="receiver-info-container" @tap="goToCust()"
								v-show="shouldShowReceiveSection">

								<view class="receiver-item">
									<text class="receiver-label">接收方客户号：</text>
									<text
										:class="['receiver-value', { 'receiver-placeholder': !receive.receiveKunnr }]">
										{{ receive.receiveKunnr || '请选择接收方' }}
									</text>
								</view>

								<view class="receiver-item">
									<text class="receiver-label">接收方客户名称：</text>
									<text :class="['receiver-value', { 'receiver-placeholder': !receive.receiveName }]">
										{{ receive.receiveName || '请选择接收方' }}
									</text>
								</view>

								<view class="receiver-item">
									<text class="receiver-label">接收方客户税号：</text>
									<text
										:class="['receiver-value', { 'receiver-placeholder': !receive.receiveSocialCreditCode }]">
										{{ receive.receiveSocialCreditCode || '请选择接收方' }}
									</text>
								</view>
							</view>
						</uni-col>
						<uni-col :span="2">
							<view class="clear-button" @click="clearReceive" v-if="receive.receiveKunnr">
								<text class="clear-icon">✖</text>
							</view>
						</uni-col>
					</uni-row>
				</view>

				<view style="margin-bottom: 5px;border-bottom: 2px solid #f5f5f5">
					<div>
						<text style="color: rgb(13, 160, 250);">补贴运价（单位：元/吨）：{{saleOrder.rebate}}</text>
					</div>
					<div>
						<text>订单号：{{saleOrder.vbeln}}</text><text
							style="color: red;">{{(saleOrder.vsnmr === '6' ? '（YT）' : saleOrder.vsnmr === '7' ? '（ZL）' : '')}}</text>
					</div>
					<div>
						<text>合同号：{{saleOrder.bstkd}}</text>
					</div>
				</view>
				<view v-for="(deliSaleOrderDetail, index) in saleOrder.deliSaleOrderDetailList" :key="index">
					<view style="margin-bottom: 5px;border-bottom: 2px solid #f5f5f5;">
						<div>
							<text>物料：{{ deliSaleOrderDetail.arktx }}</text>
						</div>
						<uni-row>
							<uni-col :span="12">
								<div>
									可申请重量：<text
										style="color: rgb(69, 207, 207);">{{ deliSaleOrderDetail.canweight }}</text>
								</div>
								<div>
									可申请包数：<text
										style="color: rgb(69, 207, 207);">{{ Math.ceil(deliSaleOrderDetail.canvolum) }}</text>
								</div>
							</uni-col>
							<uni-col :span="12">
								<div>
									<span>单价：</span>
									<span
										style="color: rgb(255, 151, 6);">{{ deliSaleOrderDetail.discountPrice ? deliSaleOrderDetail.discountPrice : deliSaleOrderDetail.price }}</span>
								</div>
							</uni-col>
						</uni-row>
						<uni-row>
							<uni-col :span="24">
								<div>
									<span>装运点：</span>
									<span style="color: rgb(255, 151, 6);">{{ deliSaleOrderDetail.vtext }}</span>
								</div>
							</uni-col>
						</uni-row>
					</view>
					<view style="margin-bottom: 5px;border-bottom: 8px solid #f5f5f5;">
						<uni-row>
							<uni-col :span="4">

								<text class="search-result">重量：</text>

							</uni-col>
							<uni-col :span="8">
								<div>
									<input type="text" v-model="deliSaleOrderDetail.applyWeight" placeholder="请输入重量"
										style="font-size:16px;font-weight: bold;" />
								</div>
							</uni-col>
							<uni-col :span="4">
								<div>
									<text class="search-result">包数：</text>

								</div>
							</uni-col>

							<uni-col :span="8">
								<div>
									<input type="number" v-model="deliSaleOrderDetail.applyVolum " placeholder="请输入申请包数"
										@input="calculateWeight(index)" style="font-size:16px; font-weight: bold;" />
								</div>
							</uni-col>
						</uni-row>
						<view>
							<uni-row>
								<uni-col :span="4">
									<text class="search-result">备注：</text>
								</uni-col>
								<uni-col :span="20">
									<input type="text" v-model="deliSaleOrderDetail.whremark" placeholder="请输入仓库备注"
										style="font-size: 16px; word-wrap: break-word; white-space: pre-wrap;font-weight: bold;" />
								</uni-col>
							</uni-row>
						</view>
					</view>
				</view>

				<view style="margin-bottom: 5px;border-bottom: 8px solid #f5f5f5;">
					<uni-row>
						<uni-col :span="20">
							<view>加急：</view>
						</uni-col>
						<uni-col :span="4">
							<!-- 	<switch :checked="false" class="custom-switch" @change="switch1Change"  color="#ff5500"
								style="transform:scale(0.7)" /> -->
							<view class="uni-list-cell uni-list-cell-pd">
								<view class="uni-list-cell-db"></view>
								<switch @change="switch1Change" color="#ff5500" />
							</view>
						</uni-col>
					</uni-row>
				</view>

				<view style="margin-bottom: 5px;border-bottom: 8px solid #f5f5f5;">
					<uni-row>
						<uni-col :span="20">
							<view>久鼎塑托：</view>
						</uni-col>
						<uni-col :span="4">
							<!-- 	<switch :checked="false" class="custom-switch" @change="switch1Change"  color="#ff5500"
								style="transform:scale(0.7)" /> -->
							<view class="uni-list-cell uni-list-cell-pd">
								<view class="uni-list-cell-db"></view>
								<switch :checked="usePlasticTray" @change="switchIfPlastic" :disabled="sutuoFlag"
									color="#ff5500" />
							</view>
						</uni-col>

					</uni-row>
				</view>

				<view style="margin-bottom: 5px;border-bottom: 8px solid #f5f5f5;">
					<uni-row>
						<uni-col :span="13">
							<view>配送方式：</view>
						</uni-col>
						<uni-col :span="11">
							<radio-group @change="radioDeliveryStatus" style="display: flex; flex-direction: row;">
								<label v-for="(item, index) in items" :key="item.value" style="margin-right: 10px;">
									<view>
										<radio :value="item.value" :checked="index === current" />
									</view>
									<view>{{item.name}}</view>
								</label>
							</radio-group>
						</uni-col>
					</uni-row>
				</view>

				<view v-if="this.deliveryStatus === '2' || this.deliveryStatus === '3'">

					<uni-row class="centered-row">
						<uni-col :span="6" class="centered-col">
							<text class="centered-text">车牌号：</text>
						</uni-col>
						<uni-col :span="12" class="centered-col">
							<lin-select :list="ecDeliverVehicles" :loading="loading" loading-text="数据加载中"
								ref="linSelect" value-key="driverVehicleNo" max-height="180" placeholder="请输入车牌号"
								@input="inputDeliverVehicle" @confirm="handleVehicleChange"
								v-model="saleOrder.driverVehicleNo" />
						</uni-col>
						<uni-col :span="6" class="centered-col">
							<button class="mini-btn" type="default" size="mini" @click="getCars">获取车号</button>
						</uni-col>
					</uni-row>
					<div>
						<uni-row>
							<uni-col :span="10">
								<text>提货司机：</text>
							</uni-col>
							<uni-col :span="14">
								<input type="text" v-model="saleOrder.driverName" placeholder="请输入提货司机" />
							</uni-col>
						</uni-row>
					</div>
					<div>
						<uni-row>
							<uni-col :span="10">
								<text>司机联系方式：</text>
							</uni-col>
							<uni-col :span="14">
								<input type="text" v-model="saleOrder.driverPhone" placeholder="请输入司机联系方式" />
							</uni-col>
						</uni-row>
					</div>
				</view>

				<div style="margin-bottom: 120px;">
					<textarea v-model="saleOrder.delivermark" placeholder="请输入物流备注" />
				</div>
			</form>
		</view>

		<view style="position: fixed; bottom: 0px; width: 100%;  align-items: center; ">
			<uni-row>
				<uni-col :span="12">
					<view>
						<button type="primary"
							style="height: 60px; display: flex; align-items: center; justify-content: center; "
							@click="goToHome">返回首页</button>
					</view>
				</uni-col>
				<uni-col :span="12">
					<view>
						<button type="primary"
							style="height: 60px; display: flex; align-items: center; justify-content: center; "
							@click="submitForm" v-preventReClick='3000'>保存</button>
					</view>
				</uni-col>
			</uni-row>
		</view>


	</view>
</template>

<script>
	import {
		getSaleOrderPage,
		getSaleOrderDetailPage,
		saveDeliverOrder,
		selectEcDeliverVehicleList,
		selectEcOneDeliverVehicleList,
		calculateExpectedCost,
		getApplyWeight,
		listAddress,
		querySAPRebate
	} from '@/api/tms/saleOrder'

	export default {
		computed: {
			vehicleCount() {
				return this.ecDeliverVehicles.length;
			},
			shouldShowReceiveSection() {
				const validTabs = ['物产逸控代', '海拓逸控代', '永成逸控代'];
				return validTabs.includes(this.saleOrder.customertab?.trim());
			}
		},
		mounted() {
			// 清除接收方缓存
			uni.removeStorageSync('receive');
			this.receive = {
				receiveKunnr: '',
				receiveName: '',
				receiveSocialCreditCode: ''
			};
			this.saleOrder.receiveKunnr = '';
			this.saleOrder.receiveName = '';
			this.saleOrder.receiveSocialCreditCode = '';

			this.mySwitch = this.$refs.mySwitch;
			const vbeln = this.$route.query.vbeln;
			if (vbeln) {
				this.saleOrder.vbeln = vbeln;
				this.search(vbeln);
			}
			const data = uni.getStorageSync('ecCustAddress');
			if (data) {
				this.ecCustAddress = data;
			}
		},
		created() {},
		data() {
			return {
				weightResultMap: new Map(),
				ifContainsFDY: false,
				ifContainsDTY: false,
				mytext2: '',
				productList2: [],
				loading: false,
				sutuoFlag: false,
				mySwitch: '',
				name1: "",
				addressList: [],
				ifUrgent: '0',
				ifPlastic: '0',
				deliveryStatus: '1',
				feight: "",
				saleName: "",
				saleOrder: {
					saleName1: "",
					saleKunnr: "",
					vbeln: "",
					kunnr: "",
					name1: "",
					canweight: "",
					canvolum: "",
					whremark: "",
					ifUrgent: "0",
					ifPlastic: "0",
					deliveryStatus: "1",
					contactsName: "",
					addressPath: "",
					contactsPhone: "",
					goodsDetailedAddress: "",
					addressPathId: "",
					delivermark: "",
					driverVehicleNo: "",
					driverName: "",
					driverPhone: "",
					expectedCost: "",
					bstkd: "",
					vsnmr: "",
					rebate: "",
				},
				sale: {
					saleName1: "",
					saleKunnr: "",
					vbeln: "",
					kunnr: "",
					name1: "",
					canweight: "",
					canvolum: "",
					whremark: "",
					ifUrgent: "0",
					ifPlastic: "0",
					deliveryStatus: "1",
					contactsName: "",
					addressPath: "",
					contactsPhone: "",
					goodsDetailedAddress: "",
					addressPathId: "",
					delivermark: "",
					driverVehicleNo: "",
					driverName: "",
					driverPhone: "",
					expectedCost: "",
					bstkd: "",
					vsnmr: "",
				},
				deliSaleOrderDetail: {
					arktx: "",
					price: "",
					applyWeight: "",
					applyVolum: "",
					canweight: "",
					canvolum: "",
					whremark: "",
				},
				deliSaleOrderDetailList: [],
				ecCustAddress: {
					custName: "",
					contactsName: "",
					contactsPhone: "",
					goodsDetailedAddress: "",
					addressPathId: "",
					addressPath: ""
				},
				receive: {
					receiveKunnr: "",
					receiveName: "",
					receiveSocialCreditCode: ""
				},
				selectedVehicle: {
					driverVehicleNo: "",
					driverName: "",
					driverPhone: "",
				},
				items: [{
						value: '1',
						name: '配送'
					},
					{
						value: '2',
						name: '自提'
					},
					{
						value: '3',
						name: '一次性自提'
					}
				],
				current: 0,
				ecDeliverVehicles: [],
				usePlasticTray: false,
			};
		},
		onShow() {
			const data = uni.getStorageSync('ecCustAddress');
			if (data) {
				this.ecCustAddress = data;
				this.getSAPRebate(data);
			}

			const dataReceive = uni.getStorageSync('receive');
			console.log('console.log(dataReceive);');
			console.log(dataReceive);
			if (dataReceive && dataReceive.receiveKunnr) {
				this.confirmReceiveSelection(dataReceive);
			}
		},
		methods: {
			// 确认接收方选择
			confirmReceiveSelection(dataReceive) {
				uni.showModal({
					title: '确认接收方信息',
					content: `您选择的接收方是：\n客户号：${dataReceive.receiveKunnr}\n客户名称：${dataReceive.receiveName}\n税号：${dataReceive.receiveSocialCreditCode}`,
					confirmText: '确认',
					cancelText: '重新选择',
					success: (res) => {
						if (res.confirm) {
							// 用户确认，设置接收方信息
							this.receive = dataReceive;
							this.saleOrder.receiveKunnr = this.receive.receiveKunnr;
							this.saleOrder.receiveName = this.receive.receiveName;
							this.saleOrder.receiveSocialCreditCode = this.receive.receiveSocialCreditCode;
						} else {
							// 用户选择重新选择，清空接收方信息
							this.clearReceive();
							// 跳转到接收方选择页面
							this.goToCust();
						}
					}
				});
			},
			getSAPRebate(value) {
				if (!this.deliSaleOrderDetailList) {
					this.saleOrder.rebate = '无可用订单明细';
					return;
				}
				const SAPRebateQueryParams = {
					vkorg: this.saleOrder.salesBranch || '',
					werks: this.deliSaleOrderDetailList[0]?.werks || '',
					matkl: this.deliSaleOrderDetailList[0]?.matkl || '',
					kunwe: this.saleOrder.weKunnr || '',
					datum: this.getCurrentDate()
				};
				if (value?.provinceCode) {
					SAPRebateQueryParams.addr1 = value.provinceCode;
				}
				if (value?.cityCode) {
					SAPRebateQueryParams.addr2 = value.cityCode;
				}
				if (value?.countyCode) {
					SAPRebateQueryParams.addr3 = value.countyCode;
				}
				if (value?.streetCode) {
					SAPRebateQueryParams.addr4 = value.streetCode;
				}
				querySAPRebate(SAPRebateQueryParams).then(response => {
					console.log('response.msg');
					console.log(response.msg);
					if (response.msg && response.msg == '缺少配置') {
						this.saleOrder.rebate = 'SAP未匹配到补贴运价';
					} else {
						this.saleOrder.rebate = response.msg;
					}
					console.log('this.saleOrder.rebate ');
					console.log(this.saleOrder.rebate);
					this.$forceUpdate();
				});
			},
			getCurrentDate() {
				const now = new Date();
				return [
					now.getFullYear(),
					String(now.getMonth() + 1).padStart(2, '0'),
					String(now.getDate()).padStart(2, '0')
				].join('');
			},
			clearAddress() {
				this.ecCustAddress.goodsDetailedAddress = '';
				this.ecCustAddress.addressPathId = '';
				this.ecCustAddress.contactsName = '';
				this.ecCustAddress.contactsPhone = ''
			},
			clearReceive() {
				this.receive.receiveKunnr = '';
				this.receive.receiveName = '';
				this.receive.receiveSocialCreditCode = '';
				this.saleOrder.receiveKunnr = '';
				this.saleOrder.receiveName = '';
				this.saleOrder.receiveSocialCreditCode = '';
				uni.setStorageSync('receive', {
					receiveKunnr: '',
					receiveName: '',
					receiveSocialCreditCode: '',
				});
			},
			getCars() {
				const childComponent = this.$refs.linSelect
				childComponent.showComboxSelect = true;
			},
			input2(val) {
				setTimeout(() => {
					this.productList2 = [{
							"name": "11"
						},
						{
							"name": "22"
						},
						{
							"name": "33"
						}
					]
				}, 1000)
			},
			input3(val) {
				setTimeout(() => {
					this.ecDeliverVehicles
				}, 1000)
			},
			inputDeliverVehicle(e) {
				//自提车牌号
				if (this.saleOrder.deliveryStatus === '2') {
					if (this.saleOrder.kunnr !== '') {
						selectEcDeliverVehicleList({
							"custNo": this.saleOrder.kunnr,
							"driverVehicleNo": e,
						}).then(response => {
							this.ecDeliverVehicles = response.rows;
							if (this.ecDeliverVehicles.length === 0) {
								const childComponent = this.$refs.linSelect
								childComponent.showComboxSelect = false;
							}
						});
					}
				}
				//一次性自提车牌号
				if (this.saleOrder.deliveryStatus === '3') {
					if (this.saleOrder.kunnr !== '') {
						selectEcOneDeliverVehicleList({
							"custNo": this.saleOrder.kunnr,
							"driverVehicleNo": e,
						}).then(response => {
							this.ecDeliverVehicles = response.rows;
							if (this.ecDeliverVehicles.length === 0) {
								const childComponent = this.$refs.linSelect
								childComponent.showComboxSelect = false;
							}
						});
					}
				}
			},
			async search(vbeln) {
				try {
					const response = await getSaleOrderPage(vbeln);
					this.saleOrder = response.data;
					if (this.saleOrder.saleName1) {
						this.saleName = this.saleOrder.saleName1;
					}
					if (this.saleOrder.weName) {
						this.weName = this.saleOrder.weName;
					}
					if (this.saleOrder.weKunnr) {
						this.weKunnr = this.saleOrder.weKunnr;
					}
					this.deliSaleOrderDetailList = this.saleOrder.deliSaleOrderDetailList = response.data
						.deliSaleOrderDetailList;

					this.deliSaleOrderDetailList.forEach(item => {
						item.canweight = 0;
						item.canvolum = 0;
					});

					await this.getDefaultAddress();

					const detailResponse = await getSaleOrderDetailPage(this.deliSaleOrderDetailList);
					this.saleOrder.deliSaleOrderDetailList = this.deliSaleOrderDetailList = detailResponse
						.data;

					if (!this.deliSaleOrderDetailList.some(item => item.arktx.includes('POY') || item.arktx
							.includes(
								'FDY'))) {
						this.saleOrder.ifPlastic = '0';
						this.usePlasticTray = false;
						this.sutuoFlag = true;
					}

					const weightPromises = this.deliSaleOrderDetailList.map(item =>
						getApplyWeight({
							"productName": item.arktx
						}).then(response => ({
							arktx: item.arktx,
							msg: response.msg
						}))
					);

					const weightResults = await Promise.all(weightPromises);
					weightResults.forEach(({
						arktx,
						msg
					}) => this.weightResultMap.set(arktx, msg));

				} catch (error) {
					console.error('查询错误:', error);
				}
			},
			getDefaultAddress() {
				listAddress({
					"custNo": this.weKunnr,
					"pageNum": 1,
					"pageSize": 1,
					"addressIsDefault": 1,
					"isValid": 0,
				}).then(response => {
					if (response.rows && response.rows.length > 0) {
						this.ecCustAddress = response.rows[0];
						if (this.ecCustAddress) {
							this.getSAPRebate(this.ecCustAddress);
						}
					}
				});
			},
			submitAddress(form) {
				addAddress(form).then(response => {});
			},
			goToAddressDetail(agKunnr, agName, weKunnr, weName) {
				uni.navigateTo({
					url: '/pages/ec/orderAddressDetail/index?agKunnr=' + agKunnr + "&agName=" +
						agName +
						"&weKunnr=" + weKunnr + "&weName=" + weName,
				});
			},
			goToCust() {
				uni.navigateTo({
					url: '/pages/ec/orderCust/index',
				});
			},
			goToHome() {
				uni.switchTab({
					url: '/pages/work/index',
				});
			},
			/** 保存按钮 */
			submitForm() {
				let thatt = this

				let deliveryStatus = this.saleOrder.deliveryStatus = this.deliveryStatus;
				let flag = true;

				let ifDTY = this.deliSaleOrderDetailList.some(detail => {
					return detail.matkl === '120';
				});
				if (ifDTY) {
					this.ifContainsDTY = true;
				}

				if ((deliveryStatus == 1 || (deliveryStatus == 3 && !this.ifContainsDTY)) && !this
					.ecCustAddress
					.contactsName) {
					flag = false;
					this.$modal.msgError("收货人不允许为空");
				};
				if ((deliveryStatus == 1 || (deliveryStatus == 3 && !this.ifContainsDTY)) && !this
					.ecCustAddress
					.goodsDetailedAddress) {
					flag = false;
					this.$modal.msgError("收货地址不允许为空");
				};
				if (this.ecCustAddress.goodsDetailedAddress) {
					this.ecCustAddress.goodsDetailedAddress = this.ecCustAddress.goodsDetailedAddress.trim();
				}
				if (this.deliSaleOrderDetailList.length > 0) {
					let shipmentPoints = new Set();
					let isValid = false;
					this.deliSaleOrderDetailList.forEach(item => {
						if (item.applyVolum) {
							if (!(Number.isInteger(parseFloat(item.applyVolum)) && item.applyVolum >
									0)) {
								this.$modal.msgError("请输入有效的申请包数！")
								flag = false;
							}
							shipmentPoints.add(item.vtext);
							//申请包数有数值时申请重量必填
							if (!item.applyWeight) {
								this.$modal.msgError("请输入有效的申请重量！")
								flag = false;
							}
							if (flag) {
								if (parseFloat(item.applyWeight) <= 0) {
									this.$modal.msgError("请输入有效的申请重量！")
									flag = false;
								}
							}
							//申请重量保留最多三位小数
							if (flag) {
								const weightStr = String(item.applyWeight);
								if (!weightStr.match(/^\d*(\.\d{0,3})?$/)) {
									this.$modal.msgError("请输入有效的申请重量，并保留最多三位小数！")
									flag = false;
								}
							}
							if (flag) {
								if (item.applyWeight > item.canweight) {
									flag = false;
									this.$modal.msgError("申请重量不能超过可申请净重！")
								}
							}
							//至少有一条数值
							if (flag) {
								isValid = true;
							}
						}
					});
					if (flag) {
						if (!isValid) {
							this.$modal.msgError("请输入申请包数和申请重量！")
							flag = false;
						}
					}
					if (flag) {
						if (shipmentPoints.size > 1) {
							this.deliSaleOrderDetailList.forEach(item => {
								if (item.applyVolum) {
									shipmentPoints.add(item.vtext);
								}
							});
						}
						if (shipmentPoints.size > 1) {
							flag = false;
							this.$modal.msgError("物料装运点不一致，请确认申请物料明细！")
						}
					}
				}
				if (flag) {
					const custName = this.saleOrder.name1;
					let saleName1 = this.saleOrder.saleName1;
					this.saleOrder.deliSaleOrderDetailList = this.deliSaleOrderDetailList;
					this.saleOrder.contactsName = this.ecCustAddress.contactsName;
					this.saleOrder.addressPath = this.ecCustAddress.addressPath;
					this.saleOrder.contactsPhone = this.ecCustAddress.contactsPhone;
					this.saleOrder.goodsDetailedAddress = this.ecCustAddress.goodsDetailedAddress;
					this.saleOrder.addressPathId = this.ecCustAddress.addressPathId;
					this.saleOrder.ifUrgent = this.ifUrgent;
					this.saleOrder.ifPlastic = this.ifPlastic;
					let ifFDY = this.saleOrder.deliSaleOrderDetailList.some(detail => {
						return detail.matkl === '140';
					});
					if (ifFDY) {
						this.ifContainsFDY = true;
					}

					if (this.deliveryStatus === '1' || (this.deliveryStatus === '3' && this.ifContainsFDY)) {
						if (this.deliveryStatus === '1') {
							if (this.saleOrder.driverVehicleNo) {
								this.saleOrder.driverVehicleNo = null;
							}
							if (this.saleOrder.oneDeliverVehicleNo) {
								this.saleOrder.oneDeliverVehicleNo = null;
							}
							if (this.saleOrder.driverName) {
								this.saleOrder.driverName = null;
							}
							if (this.saleOrder.driverPhone) {
								this.saleOrder.driverPhone = null;
							}
						}

						this.sale = {
							...this.saleOrder,
							deliSaleOrderDetailList: []
						};
						const details = [];
						this.saleOrder.deliSaleOrderDetailList.forEach(item => {
							if (item.applyVolum) {
								if (item.applyWeight) {
									details.push(item);
								}
							}
						});
						this.sale.deliSaleOrderDetailList = details;

						calculateExpectedCost(this.sale).then(response => {

							const checked = response.msg;
							this.saleOrder.expectedCost = response.msg;;
							const saleOrder = this.saleOrder;


							if (checked) {
								uni.showModal({
									title: '运费',
									content: checked,
									success: function(res) {
										if (res.confirm) {
											saveDeliverOrder(saleOrder).then(response => {
												// uni.showToast({
												// 	title: '新增成功',
												// 	duration: 2000
												// });

												// uni.navigateTo({
												// 	url: '/pages/ec/saleOrderDetail/index?custName=' +
												// 		custName,
												// });
												// this.$tab.switchTab('/pages/ec/saleOrderDetail/index?custName=' + custName);
												uni.showModal({
													title: '提示',
													content: '新增成功',
													showCancel: false,
													confirmText: '确定',
													success: function(
														res) {
														if (res
															.confirm) {
															setTimeout(
																function() {
																	// 跳转至申请订单页面
																	uni.navigateTo({
																		url: '/pages/ec/saleOrderDetail/index?custName=' +
																			saleName1
																	});
																},
																1000
															);
														}
													}
												});

											});
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
							}
						});

					} else {

						let falgVhicle = true;
						if (!this.saleOrder.driverPhone || !this.saleOrder.driverName || !this.saleOrder
							.driverVehicleNo) {
							falgVhicle = false;
							this.$modal.msgError("车辆信息(车牌号、司机、司机联系方式)不允许为空！");
						};
						if (falgVhicle) {
							this.saleOrder.expectedCost = '';
							saveDeliverOrder(this.saleOrder).then(response => {
								uni.showModal({
									title: '提示',
									content: '新增成功',
									showCancel: false,
									confirmText: '确定'
								});
								uni.showModal({
									title: '提示',
									content: '新增成功',
									showCancel: false,
									confirmText: '确定',
									success: function(res) {
										if (res.confirm) {
											// 延迟两秒后执行其他操作
											setTimeout(function() {
												// 在这里执行你想要的其他操作
												uni.navigateTo({
													url: '/pages/ec/saleOrderDetail/index?custName=' +
														saleName1
												});
											}, 1000);
										}
									}
								});

								// uni.navigateTo({
								// 	url: '/pages/ec/saleOrderDetail/index?custName=' + custName,
								// });
								// this.$tab.redirectTo('/pages/ec/saleOrderDetail/index?custName=' + custName);

							});
						}
					}
				}
			},
			switch1Change(e) {
				const checked = e.detail.value;
				if (checked) {
					this.ifUrgent = '1';
				} else {
					this.ifUrgent = '0';
				}
				// this.checkAddType();
			},
			switchIfPlastic(e) {
				const checked = e.detail.value;
				if (checked) {
					this.saleOrder.ifPlastic = '1';
					this.ifPlastic = '1';
				} else {
					this.saleOrder.ifPlastic = '0';
					this.ifPlastic = '0';
				}
				if (this.saleOrder.ifPlastic && !this.deliSaleOrderDetailList.some(item => item.arktx.includes(
							'POY') ||
						item
						.arktx.includes('FDY'))) {
					this.saleOrder.ifPlastic = '0';

					this.usePlasticTray = false;

					this.$forceUpdate()
					alert('只有POY或者FDY才可以使用塑托!');
					return
				}
				this.checkAddType();
			},
			radioDeliveryStatus(e) {
				this.saleOrder.deliveryStatus = e.detail.value;
				this.deliveryStatus = e.detail.value;
				this.handleDeliveryStatusChange();
			},
			checkAddType() {

				if (this.saleOrder.ifPlastic && !this.deliSaleOrderDetailList.some(item => item.arktx.includes(
							'POY') ||
						item
						.arktx.includes('FDY'))) {
					this.saleOrder.ifPlastic = '0';

					this.usePlasticTray = false;
					this.$forceUpdate()
					alert('只有POY或者FDY才可以使用塑托!');
					return
				}
				if (this.saleOrder.ifPlastic == '1') {
					this.deliSaleOrderDetailList.forEach(item => {
						if (item.whremark) {
							item.whremark = item.whremark + '久鼎塑托';
						} else {
							item.whremark = '久鼎塑托';
						}
					});
				} else {
					this.deliSaleOrderDetailList.forEach(item => {
						if (item.whremark) {
							item.whremark = '';
						}
					});
				}
			},
			handleDeliveryStatusChange() {
				//自提车牌号
				if (this.saleOrder.deliveryStatus === '2') {
					if (this.saleOrder.kunnr !== '') {
						this.fetchDeliverVehicle();
					}
				}
				//一次性自提车牌号
				if (this.saleOrder.deliveryStatus === '3') {
					if (this.saleOrder.kunnr !== '') {
						this.fetchOneDeliverVehicle();
					}
				}
			},
			fetchDeliverVehicle() {
				selectEcDeliverVehicleList({
					"custNo": this.saleOrder.kunnr
				}).then(response => {
					this.ecDeliverVehicles = response.rows;
				});
			},
			fetchOneDeliverVehicle() {
				selectEcOneDeliverVehicleList({
					"custNo": this.saleOrder.kunnr
				}).then(response => {
					this.ecDeliverVehicles = response.rows;
				});
				this.input3();
			},
			handleVehicleChange(value) {
				const selectedVehicle = this.ecDeliverVehicles.find(vehicle => vehicle.driverVehicleNo === this
					.saleOrder
					.driverVehicleNo);
				this.saleOrder.driverName = selectedVehicle.driverName;
				this.saleOrder.driverPhone = selectedVehicle.driverPhone;
			},
			selectBlur(e) {
				this.form.driverVehicleNo = e.target.value;
				this.$forceUpdate();
			},
			calculateWeight(index) {
				let applyVolum = this.deliSaleOrderDetailList[index].applyVolum;
				// 使用正则表达式检查是否为正整数
				if (/^[1-9]\d*$/.test(applyVolum)) {
					// 如果是正整数，更新数据模型
					this.deliSaleOrderDetailList[index].applyVolum = applyVolum;
				} else {
					// 如果不是正整数，将输入框的值设为空或其他处理方式
					this.deliSaleOrderDetailList[index].applyVolum = Math.abs(this.deliSaleOrderDetailList[
							index]
						.applyVolum);
				}
				let arktx = this.deliSaleOrderDetailList[index].arktx;
				let weight = this.weightResultMap.get(arktx);
				if (weight !== undefined && weight != '') {
					this.deliSaleOrderDetailList[index].applyWeight = (applyVolum * weight).toFixed(3) <
						0.0001 ? '' : (applyVolum * weight).toFixed(3);
					if (this.deliSaleOrderDetailList[index].applyWeight > this.deliSaleOrderDetailList[index]
						.canweight) {
						this.deliSaleOrderDetailList[index].applyWeight = this.deliSaleOrderDetailList[index]
							.canweight
						this.$modal.msgError("按照标准重量，包数超出，请核实申请数量", 6000);
					}
				}

			},
		},
	};
</script>

<style scoped>
	.centered-row {
		display: flex;
		justify-content: space-between;
		/* 在每个uni-col之间平均分配空间 */
		margin: -1px;
		/* 为了在每个uni-col之间创建2px的间隔，这里使用负边距 */
	}

	.centered-col {
		display: flex;
		flex-direction: column;
		align-items: center;
		/* 内容垂直居中 */
		margin: 1px;
		/* 为了在每个uni-col内创建2px的间隔，这里使用正边距 */
	}

	.centered-text {
		text-align: center;
		/* 水平居中 */
	}

	.container {
		dispaly: flex;
		flex-direction: row;
		flex: auto;
		background-color: #fff
	}

	.page-title {
		background: #3e7baf;
		color: #fff;
		text-align: center;
		font-size: 1.3rem;
		font-weight: "300";
		margin-bottom: 20px;
	}

	.search-results-container {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 200%;
		/* 设置高度为内容的高度的两倍 */
		padding: 3px;
		margin-bottom: 100px;
		/* 设置内边距 */
		background-color: #fff;
		/* 设置背景色 */
	}

	.search-result {
		flex: 2;
		/* 使每个内部元素均等分布 */
		margin-bottom: 10px;

		/* 设置底部边距 */
		background-color: #fff;
		/* 设置底部边框颜色 */
		/* 设置内边距 */
		font-size: 16px;
	}

	.search-results-container div {
		padding: 3px;
		display: flex;
	}

	.style-switch {
		color: #0000FF;
	}

	.custom-switch.on {
		background-color: blue;
	}

	.clear-button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 24px;
		height: 24px;
		border: 2px solid #C0C4CC;
		border-radius: 50%;
		padding: 0;
		cursor: pointer;
		margin-top: 4px;
	}

	.clear-icon {
		color: #C0C4CC;
		font-size: 14px;
	}

	.receiver-info-container {
		padding-top: 10px;
		padding-left: 14px;
	}

	.receiver-item {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
		line-height: 1.5;
	}

	.receiver-label {
		color: #666;
		font-size: 14px;
		min-width: 120px;
		font-weight: 500;
	}

	.receiver-value {
		color: #333;
		font-size: 14px;
		flex: 1;
		font-weight: 400;
	}

	.receiver-placeholder {
		color: #ff4d4f;
		font-style: italic;
		font-weight: 500;
	}
</style>